package com.mesnac.comm.xml.dom;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class DomXmlTool {
	
	private DocumentBuilder builder;
	private Document doc;

	public DomXmlTool(String filePath){
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		//允许名字空间
		factory.setNamespaceAware(true);
		//允许验证 
		factory.setValidating(true);
		try{
			builder = factory.newDocumentBuilder();
			createDoc(filePath);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 解析一个xml文档，并获得doc
	 * @param filePath
	 * @return
	 */
	public Document createDoc(String filePath){
		try{
			doc = builder.parse(filePath);
		}catch(Exception e){
			e.printStackTrace();
		}
		return doc;
	}
	/**
	 * 获得根节点
	 * @return
	 */
	public Element getRootElement(){
		Element rootElement = doc.getDocumentElement();
		return rootElement;
	}
	/**
	 * 根据Tag名字获得节点
	 * @param name
	 * @return
	 */
	public NodeList getChildElement(String name){
		Element root = doc.getDocumentElement();
		NodeList childList = root.getElementsByTagName(name);
		return childList;
	}
	/**
	 * 创建xml文档的例子
	 * @param path
	 */
	
	public void createXml(String path){
		Document doc = null;
		doc = builder.newDocument();
		Element root = doc.createElement("es");
		doc.appendChild(root);
		Element student = doc.createElement("student");
		student.setAttribute("sex", "male");
		root.appendChild(student);
		Element name = doc.createElement("姓名");   
		student.appendChild(name);   
		Text tName = doc.createTextNode("dd");   
		name.appendChild(tName);  
		Element age = doc.createElement("年龄");   
		student.appendChild(age);   
		Text tAge = doc.createTextNode(String.valueOf(1));   
		age.appendChild(tAge);  
	}
}
